<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Support\Facades\Cookie;

class BaseController extends Controller
{

    protected $model;
    protected $error;
    protected $myUser;

    // 管理后台接口

    // 初始化
    public function initialize()
    {
        $opt  = $this->optLogic();
        $user = $this->myUser();
        // 参数
        $controller = $opt->getData('controller', 'home', 'trim');
        $action     = $opt->getData('action', 'home', 'trim');

        // 权限判断 通过控制器来判断
        $this->myUser = $user;


        // 所有的人都可以操作的控制器：测试，登录，
        if(!in_array($controller, ['account', 'test', 'search', 'deal',])){
            // TODO 必须登录
            $this->throwIf(empty($user), '请登录后在操作！');

            // TODO 公共权限
            //   发布文章快讯新鲜事：可以选择用户，选择话题
            $con_act = $controller.'_'.$action;
            $hasRole = in_array($con_act, ['user_lists', 'topic_lists',]);

            // 判断权限：是否含有当前控制器 => 如果不存在 则没有权限
            // 如果是1 超级管理员 所有权限都有
            /*if(($user['uid'] != 1) || empty($hasRole)){
                // 权限处理
                // $role = $user['role'] ?? '[]';
                // $role = json_decode($role, true);
                $role = array_column($user['role'], 'role');

                // 其中几个特殊控制器
                $all         = [];
                $controllers = ['point', 'business', 'dispatch', 'abroad', 'news', 'author', 'image',];
                foreach($user['role'] as $item){
                    $_role = $item['role'];
                    if(in_array($_role, $controllers)){
                        $all[] = $_role.'-cate';
                        $all[] = $_role.'-article';
                        $all[] = 'comment';
                    }
                    // 栏目中，获取文章列表
                    if($_role == 'cate'){
                        $all[] = 'article';
                    }
                    $all[] = $_role;
                }

                $this->throwIf(!in_array($controller, $all), '你没有该操作权限！！');
            }*/
            /*if($user['uid'] == 1){
                $this->throwIf(!$user['hasRole'], '你没有该操作权限！！');
            }*/
        }
    }

    // 获取用户以及权限
    protected function myUser()
    {
        $opt  = $this->optLogic();
        $user = $opt->token('admin', 'back-token');
        $opt->throwIf($user === false, $opt->getError(), LOGIN_ERROR);
        if(empty($user)){
            return [];
        }

        //$hasRole     = true;
        //makeRoles($roles, $is_parent = true);
        // 组合
        $user['uid'] = $user['id'];

        return $user;
    }


    ###############################################################################################
    ## 数据操作
    ###############################################################################################
    // 查询统计
    public function count()
    {
        $manage = $this->checkManage($this->model);
        if($manage === false){
            return $this->error($manage->getError());
        }

        $result = $manage->onCount();

        return $this->success($result);
    }

    // 返回列表数据
    public function lists()
    {
        $manage = $this->checkManage($this->model);
        if($manage === false){
            return $this->error($manage->getError());
        }

        $lists = $manage->onPageLists();
        if($lists === false){
            return $this->error($manage->getError());
        }

        return $this->success($lists);
    }

    // 删除
    public function delete()
    {
        $manage = $this->checkManage($this->model);
        if($manage === false){
            return $this->error($manage->getError());
        }

        $result = $manage->onDelete();
        if($result === false){
            return $this->error($manage->getError());
        }

        return $this->success();
    }

    // 软删除
    public function soft()
    {
        $manage = $this->checkManage($this->model);
        if($manage === false){
            return $this->error($manage->getError());
        }

        $result = $manage->onSoft();
        if($result === false){
            return $this->error($manage->getError());
        }

        return $this->success();
    }

    // 启用禁用
    public function status()
    {
        $manage = $this->checkManage($this->model);
        if($manage === false){
            return $this->error($manage->getError());
        }

        $result = $manage->onStatus();
        if($result === false){
            return $this->error($manage->getError());
        }

        return $this->success([], '更新成功！');
    }

    // 修改
    public function edit()
    {
        $manage = $this->checkManage($this->model);
        if($manage === false){
            return $this->error($manage->getError());
        }

        $result = $manage->onEdit();
        if($result === false){
            return $this->error($manage->getError());
        }

        return $this->success();
    }

    // 添加
    public function add()
    {
        $manage = $this->checkManage($this->model);
        if($manage === false){
            return $this->error($manage->getError());
        }

        $result = $manage->onAdd();
        if($result === false){
            return $this->error($manage->getError());
        }

        return $this->success();
    }

    // 详情：修改的时候要使用的
    public function show()
    {
        $manage = $this->checkManage($this->model);
        if($manage === false){
            return $this->error($manage->getError());
        }

        $info = $manage->onShow();
        if($info === false){
            return $this->error($manage->getError());
        }

        return $this->success($info);
    }

    ###############################################################################################

    // 判断操作模型是否存在
    protected function checkManage($manage = '')
    {
        $this->throwIf(empty($manage), '请指定操作！！');
        // 模型 与 查询
        $manage = 'App\Manage\\'.ucwords($manage).'Manage';
        if(!class_exists($manage)){
            $request = request();
            $real_ip = $request->getClientIp();
            $test_ip = env('TEST_IP');
            $this->throwIf(true, '操作不存在！！');

            return false;
        }

        return new $manage;
    }

    // 抛出异常
    protected function throwIf($condition, $msg, $code = 400)
    {
        if($condition){
            throw new \RuntimeException($msg, $code);
        }
    }

}


